﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using SalePartial.BLL;
using System.Data;
using SalePartial.Utility;
using Telerik.Web.UI;
using SalePartial.Model;
using XunPan.Web.Globals;

public partial class Trade_trade_item : System.Web.UI.Page
{
     
    protected void Page_Load(object sender, System.EventArgs e)
    {
        //Response.Write(Session["s_companyID_guid"]);

        if (!IsPostBack)
        {
            if (ddlType.Text == "1")
            {
                rtvCategoryTree.DataSourceID = "xdsWareCubes";
            }
            else if (ddlType.Text == "2")
            {
                rtvCategoryTree.DataSourceID = "xdsProcess";
            }
            rtvCategoryTree.DataBind();
            if (ddlSellerRoot.Text == "own")
            {
                //XPFavoriteVedor favorVedor = new XPFavoriteVedor();
                //DataSet dsFavor = favorVedor.SelectByCompanyID((Guid)Session["s_companyID_guid"]);
                //radgridVendorList.DataSource = dsFavor;
                //radgridVendorList.DataBind();
                radgridVendorList.DataSourceID = "SqlDataSource1";
                
            }
            else if (ddlSellerRoot.Text == "all")
            {
                radgridVendorList.DataSourceID = "odsVendorList";

            }
            //radgridVendorList.DataBind();
           
            //UserBLL.StoreUserInfoToSession("jiang@www.com");
            LoginUserType type = RoleControlManager.checkUserAuthority(User.Identity.Name);
            if(type ==LoginUserType.FREE_PURCHASE
                || type == LoginUserType.CERT_PURCHASE || type == LoginUserType.CERT_SUP_PUR
                || type==LoginUserType.FREE_SUP_PUR)
            //if (Roles.IsUserInRole(User.Identity.Name, "Purchase"))
            {

                if (Session["s_userID_guid"] == null || Session["s_companyID_guid"] == null)
                {
                    //★★test★★
                    bool result = UserBLL.StoreUserInfoToSession(User.Identity.Name);
                    //bool result = UserBLL.StoreUserInfoToSession("jiang@www.com");
                }


                Guid userid = (Guid)Session["s_userID_guid"];
                Guid companyid = (Guid)Session["s_companyID_guid"];


                //Dim k As New Guid("ae24df22-2c6e-431a-8c23-2bbf510e4b81")
                //Dim m As New Guid("68ec6c06-7c46-4e7c-91a2-0d775f8f07ec")
                //Session.Add("s_companyID_guid", k)
                //Session.Add("s_userID_guid", m)

                //检查数据条件
                if (HttpContext.Current.Session["c_selectedVendors_dt"]!=null)
                {
                    //表明页面是由其他页面transfer过来发布新询盘
                    //保留已选择供应商
                    Session["s_selectedVendors_dt"] = HttpContext.Current.Session["c_selectedVendors_dt"];


                    //设置为非公开询盘
                    rblPublic.SelectedValue = "0";
                    pnlVendorSelection.Enabled = true;

                }

                PopulateGrid();

                XPCompany xpcompany = new XPCompany();
                DataSet ds = xpcompany.SelectSingle(companyid);

                dvBuyer.DataSource = ds;
                dvBuyer.DataBind();

                rdpAssignDate.MinDate = DateTime.Now;
                rdpDelivery.MinDate = DateTime.Now;
                rdpExpDate.MinDate = DateTime.Now;
            }
            else
            {
                Response.Redirect(GlobalSetting.UrlHomePage, true);

            }
        }
        

    }

    protected void change(object sender, System.EventArgs e)
    {
        if (ddlType.Text == "1")
        {
            rtvCategoryTree.DataSourceID = "xdsWareCubes";
        }
        else if (ddlType.Text == "2")
        {
            rtvCategoryTree.DataSourceID = "xdsProcess";
        }
        rtvCategoryTree.DataBind();
    }



    /// <summary>
    /// 创建数据表以存储用户选择的种类信息并将其放入session中
    /// 
    /// </summary>
    /// <remarks></remarks>

    private void PopulateGrid()
    {
        DataTable dt = (DataTable)Session["s_selectedCategory_dt"];
        if (dt == null)
        {
            dt = new DataTable();
            dt.Columns.Add("Text");
            dt.Columns.Add("Value");
            Session.Add("s_selectedCategory_dt", dt);
        }
        radgridSelectedCategory.DataSource = dt;
        radgridSelectedCategory.DataBind();

        DataTable dtvendors = (DataTable)Session["s_selectedVendors_dt"];
        if (dtvendors == null)
        {
            dtvendors = new DataTable();
            dtvendors.Columns.Add("CompanyID");
            dtvendors.Columns.Add("CompanyName");
            Session.Add("s_selectedVendors_dt", dtvendors);
        }

        rgridTargetVendors.DataSource = dtvendors;
        rgridTargetVendors.DataBind();

    }

    protected void rcbProvince_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox cbox = (RadComboBox)o;


        if (cbox.SelectedIndex > 0)
        {
            RadComboBox citybox = (RadComboBox)cbox.Parent.FindControl("rcbCity");
            if (citybox != null)
            {
                LoadCites(citybox, e.Value);
            }

        }
        else
        {
            cbox.Text = "";
            //cbox.Items.Clear();
        }

    }


    private void LoadProvinces(RadComboBox target, string province="", string city="")
    {
        target.Items.Clear();

        target.DataTextField = "ProvinceName";
        target.DataValueField = "ID";
        target.DataSource = xdsProvinces;

        target.DataBind();
        target.AppendDataBoundItems = true;
        target.Items.Insert(0, new RadComboBoxItem("- 所有省份 -"));


        if (!province.Equals(""))
        {
            foreach (RadComboBoxItem item in target.Items)
            {
                if (item.Text == province)
                {
                    item.Selected = true;
                    break; // TODO: might not be correct. Was : Exit For

                }
            }

            RadComboBox citybox = (RadComboBox)target.Parent.FindControl("rcbCity");
            if (citybox != null)
            {
                LoadCites(citybox, target.SelectedValue, city);
            }
        }
        //insert the first item

    }

    private void LoadCites(RadComboBox target, string provinceID, string city = "")
    {
        xdsCities.XPath = "/Cities/City[@PID='" + provinceID + "']";
        target.DataTextField = "CityName";
        target.DataValueField = "ID";
        target.DataSource = xdsCities;
        target.DataBind();
        target.Items.Insert(0, new RadComboBoxItem("- 所有城市 -"));

        if (!city.Equals(""))
        {
            foreach (RadComboBoxItem item in target.Items)
            {
                if (item.Text == city)
                {
                    item.Selected = true;
                    break; // TODO: might not be correct. Was : Exit For
                }
            }

        }


    }

    protected void dvAddress_ItemCreated(object sender, System.EventArgs e)
    {
        if (dvAddress.CurrentMode == DetailsViewMode.Insert)
        {
            Control rcb = dvAddress.Rows[1].FindControl("rcbProvince");
            try
            {
                RadComboBox cbox = (RadComboBox)rcb;
                LoadProvinces(cbox);

            }
            catch (Exception ex)
            {
            }


        }
    }

    protected void dvAddress_ItemInserted(object sender, System.Web.UI.WebControls.DetailsViewInsertedEventArgs e)
    {
        SelectedDeliveryAddress.Value = e.Values["AddressID"].ToString();
        SelectedDelivAddrSave.Text = SelectedDeliveryAddress.Value;
        gvAddressList.DataBind();

        //XPDeliveryAddres xpDeliAdd = new XPDeliveryAddres();
        //XPDeliveryAddresInfo info = new XPDeliveryAddresInfo();
        //info.AddressID = new Guid( e.Values["AddressID"].ToString());
        //info.CompanyID = new Guid(e.Values["CompanyID"].ToString());
        //info.Contact = e.Values["Contact"]==null ? "":e.Values["Contact"].ToString();
        //info.Street =e.Values["Street"]==null?"": e.Values["Street"].ToString();
        //info.City = e.Values["City"] == null ? "" : e.Values["City"].ToString();
        //info.Province = e.Values["Province"] == null ? "" : e.Values["Province"].ToString();
        //info.Country = e.Values["Country"] == null ? "" : e.Values["Country"].ToString();
        //info.Postcode = e.Values["Postcode"] == null ? "" : e.Values["Postcode"].ToString();
        //info.Phone = e.Values["Phone"] == null ? "" : e.Values["Phone"].ToString();
        //info.CellPhone = e.Values["CellPhone"] == null ? "" : e.Values["CellPhone"].ToString();
        //info.IsDefault = Convert.ToBoolean(e.Values["isDefault"] == null ? "false" : e.Values["isDefault"].ToString());
        //info.CreateDate = Convert.ToDateTime( e.Values["CreateDate"].ToString());
        //xpDeliAdd.Insert(info);
    }


    protected void dvAddress_ItemInserting(object sender, System.Web.UI.WebControls.DetailsViewInsertEventArgs e)
    {
        e.Values["AddressID"] = Guid.NewGuid();
        e.Values["CompanyID"] = Session["s_companyID_guid"];
        e.Values["CreateDate"] = DateTime.Now;


        try
        {

           
            Control rcb = dvAddress.Rows[1].FindControl("rcbCountry");
            RadComboBox cbox = (RadComboBox)rcb;
            e.Values["Country"] = cbox.SelectedItem.Text;

            rcb = dvAddress.Rows[1].FindControl("rcbProvince");
            cbox = (RadComboBox)rcb;
            e.Values["Province"] = cbox.SelectedItem.Text;

            rcb = dvAddress.Rows[1].FindControl("rcbCity");
            cbox = (RadComboBox)rcb;
            e.Values["City"] = cbox.SelectedItem.Text;
        }
        catch (Exception ex)
        {
        }

    }



    protected void SelectedDeliveryAddress_Load(object sender, System.EventArgs e)
    {
        //页面第一次加载将默认的运送地址设为已经选择的地址
        //若无运送地址，则显示新建
        //若页面为回发的页面会判断是否已选择运送地址


        if (!Page.IsPostBack)
        {
            Guid k = (Guid)Session["s_companyID_guid"];

            XPDeliveryAddres xpDeliAdd = new XPDeliveryAddres();
            DataSet ds = xpDeliAdd.SelectByCompanyID(k);

            string expression = null;
            expression = "IsDefault = 1";
            DataRow[] foundRows = null;
            foundRows = ds.Tables[0].Select(expression);
            if (foundRows.Length > 0)
            {
                k = (Guid)foundRows[0][0];
                SelectedDeliveryAddress.Value = k.ToString();
                SelectedDelivAddrSave.Text = SelectedDeliveryAddress.Value;
            }
            else
            {
                dvAddress.ChangeMode(DetailsViewMode.Insert);
            }
        }
    }

    protected void gvAddressList_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (gvAddressList.DataKeys[e.Row.RowIndex]["AddressID"].ToString().ToLower() == SelectedDeliveryAddress.Value.ToLower())
            {
                gvAddressList.SelectedIndex = e.Row.RowIndex;
                e.Row.RowState = DataControlRowState.Selected;

            }
        }


    }


    protected void gvAddressList_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        SelectedDeliveryAddress.Value = gvAddressList.SelectedValue.ToString();
        SelectedDelivAddrSave.Text = SelectedDeliveryAddress.Value;
    }


   
    //protected void btFindSeller(object sender, System.EventArgs e)
    //{
    //    if()
    //    {}
    //}
    protected void btSubmit_Click(object sender, System.EventArgs e)
    {
        //验证需要或已经上传的文件格式
        if (radUploadDrawing.InvalidFiles.Count > 0)
        {
            lblMsg.Text = "图纸文件大小超出范围";
            return;


        }
        else
        {

        }

        if (radUploadImage.InvalidFiles.Count > 0)
        {
            lblMsg.Text = "图片尺寸超出范围";
            return;

        }

        if (radUploadAttachment.InvalidFiles.Count > 0)
        {
            lblMsg.Text = "附件格式不正确或者大小超出范围";//ning  格式不正确或者大小超出限制，这里我还需要再修改
            return;


        }

        if (rblPublic.SelectedValue == "0")
        {
            DataTable dt = (DataTable)Session["s_selectedVendors_dt"];
            if (dt == null || dt.Rows.Count == 0)
            {
                lblMsg.Text = "请选择供应商";
                return;
            }
        }



        //验证选择的工艺类型
        DataTable dtCate = (DataTable)Session["s_selectedCategory_dt"];
        string categoryString = "";
        if (dtCate.Rows.Count > 0)
        {
            //标准零部件
            foreach (DataRow dr in dtCate.Rows)
            {
                categoryString = categoryString + dr["Value"].ToString() + "<>";
            }
            categoryString = categoryString.Remove(categoryString.Length - 2);
        }
        else
        {
            lblMsg.Text = "未选择工艺或产品类型";
            return;
        }
        
        string oldfilename = null;
        string newfilename = null;
        string oldfilepath = null;
        string newfilepath = null;

        XPInquiryInfo inquiry = new XPInquiryInfo();
        string od = inquiry.InquiryID.ToString();

        var _with1 = inquiry;

        //验证必要的数据字段

        if (string.IsNullOrEmpty(tbName.Text.Trim()))
        {
            lblMsg.Text = "请输入零件名称";
            return;
        }
        else
        {
            _with1.PartName = tbName.Text;
            _with1.PartModelName = categoryString;
        }

        if (rdpAssignDate.SelectedDate == null)
        {
            lblMsg.Text = "请选择授盘期限";
            return;

        }
        else
        {
            _with1.AssignDate = (DateTime)rdpAssignDate.SelectedDate;
        }

        if (rdpDelivery.SelectedDate == null)
        {
            lblMsg.Text = "请选择交货期限";
            return;
        }
        else
        {
            _with1.DeliveryDate = (DateTime)rdpDelivery.SelectedDate;
        }

        if (rdpExpDate.SelectedDate == null)
        {
            lblMsg.Text = "请选择询盘期限";
            return;
        }
        else
        {
            _with1.ExpireDate = (DateTime)rdpExpDate.SelectedDate;
        }

        if (rntbQty1.Value == null)
        {
            lblMsg.Text = "请输入采购数量";
            return;

        }
        else
        {
            _with1.Quantity1 = rntbQty1.Value.ToString();
        }

        if (rntbQty2.Value == null)
        {
            lblMsg.Text = "请输入采购数量";
            return;

        }
        else
        {
            _with1.Quantity2 = rntbQty2.Value.ToString();
            _with1.Quantity3 = rntbQty3.Value.ToString();
        }

        if (rntbQty3.Value == null)
        {
            lblMsg.Text = "请输入采购数量";
            return;

        }
        else
        {
            _with1.Quantity3 = rntbQty3.Value.ToString();
        }

        //系统设置字段
        _with1.UserID = (Guid)Session["s_userID_guid"];
        _with1.CompanyID = (Guid)Session["s_companyID_guid"];
        //设置询盘发布状态
        _with1.InquiryStatus = _with1.InquiryStatus.Remove(1, 1);
        _with1.InquiryStatus = _with1.InquiryStatus.Insert(1, "1");

        _with1.InquiryType = ddlType.SelectedValue.ToString();
        if (SelectedDelivAddrSave.Text == "")
        {
            lblMsg.Text = "请输入收货人地址等信息";
            return;
        }
        _with1.AddressID = new Guid(SelectedDelivAddrSave.Text);
        _with1.Currency = ddlCurrency.SelectedValue;
        _with1.Unit = ddlUnit.SelectedValue;
        _with1.PaymentMethod = rblPayMethod.SelectedValue;
        _with1.Delivery = rblDelivery.SelectedValue;
        _with1.DeliveryComment = tbDelvryComment.Text;
        _with1.IsPublic = rblPublic.SelectedValue == "0" ? false : true;


        //可选择字段
        _with1.PartDescription = tbDescription.Text;
        _with1.PartMaterial = tbMaterial.Text;
        _with1.PartNumber = tbNumber.Text;
        _with1.PartWhereUsed = tbWhereused.Text;
        _with1.PrepaidAmount = rntbPrepaid.Value.ToString();
        _with1.PurchasePurpose = tbPurpose.Text;
        _with1.RefAtchComment = tbAtchComment.Text;
        if (rntbRefVolum.Value != null)
        {
            _with1.PurchaseVolum = rntbRefVolum.Value.ToString();
        }
        else
        {
            _with1.PurchaseVolum = "";
        }
        if (rntbRefPrice.Value != null)
        {
            _with1.RefPrice = rntbRefPrice.Value.ToString();
        }
        else
        {
            _with1.RefPrice = "";
        }



        //此处处理上传的模型/图纸文件


        if (radUploadDrawing.UploadedFiles.Count > 0)
        {
            oldfilename = radUploadDrawing.UploadedFiles[0].GetName();
            Trace.Warn(oldfilename);//ning  这里服务器中上传失败，我根据【注册模块】中上传logo的代码进行修改，上传成功
            oldfilepath = Server.MapPath(radUploadDrawing.TargetFolder) + "\\" + oldfilename;

            Trace.Warn(oldfilepath);


            newfilename = FileUtility.CreateUniqueFileName(oldfilename);
            //newfilepath = GlobalSetting.TradeDrawingFolderServerPath + newfilename;ning
            newfilepath = Server.MapPath(radUploadDrawing.TargetFolder) + "\\" + newfilename;
            //Trace.Warn(newfilepath);ning

            System.IO.File.Move(oldfilepath, newfilepath);

            inquiry.PartModelFile = GlobalSetting.TradeDrawingFolderVirtualPath + newfilename;
        }
        else
        {
            inquiry.PartModelFile = "";
        }


        //此处处理上传的零件图片文件，包括缩略图


        if (radUploadImage.UploadedFiles.Count > 0)
        {
            oldfilename = radUploadImage.UploadedFiles[0].GetName();
           
            oldfilepath = Server.MapPath(radUploadImage.TargetFolder) + "\\" + oldfilename;

            Trace.Warn(oldfilepath);


            newfilename = FileUtility.CreateUniqueFileName(oldfilename);
            newfilepath = GlobalSetting.TradeImageFolderServerPath + newfilename;
            
            Trace.Warn(newfilepath);

            System.IO.File.Move(oldfilepath, newfilepath);
            inquiry.PartPicture = GlobalSetting.TradeImageFolderVirtualPath + newfilename;


            //此处处理缩略图
            byte[] image = ImageUtility.ModifyImage(System.IO.File.ReadAllBytes(newfilepath), GlobalSetting.ImageThumbSize, -1, radUploadImage.UploadedFiles[0].ContentType, true);

            newfilename = System.IO.Path.GetFileNameWithoutExtension(newfilename) + "_thumb_" + GlobalSetting.ImageThumbSize.ToString() + System.IO.Path.GetExtension(newfilename);
            newfilepath = GlobalSetting.TradeImageFolderServerPath + newfilename;


            System.IO.File.WriteAllBytes(newfilepath, image);
            inquiry.PartThumbnail = GlobalSetting.TradeImageFolderVirtualPath + newfilename;

        }
        else
        {
            inquiry.PartPicture = "";
            inquiry.PartThumbnail = "";
        }


        //此处处理上传的各种附件


        if (radUploadAttachment.UploadedFiles.Count > 0)
        {
            oldfilename = radUploadAttachment.UploadedFiles[0].GetName();
            oldfilepath = Server.MapPath(radUploadAttachment.TargetFolder) + "\\" + oldfilename;

            Trace.Warn(oldfilepath);


            newfilename = FileUtility.CreateUniqueFileName(oldfilename);
            //newfilepath = GlobalSetting.TradeFileFolderServerPath + newfilename;//ning   同上
            newfilepath = Server.MapPath(radUploadAttachment.TargetFolder) + "\\" + newfilename;

            Trace.Warn(newfilepath);

            System.IO.File.Move(oldfilepath, newfilepath);
            inquiry.RefAttachment = GlobalSetting.TradeFileFolderVirtualPath + newfilename;
        }
        else
        {
            inquiry.RefAttachment = "";

        }

        var _with2 = inquiry;
        //Trace.Warn(_with2.CreateDate.ToString);
        //Trace.Warn(_with2.DeleteDate.ToString);
        //Trace.Warn(_with2.LastSaveDate.ToString);
        //Trace.Warn(_with2.ModerationDate.ToString);
        //Trace.Warn(_with2.SubmitDate.ToString);

        od = inquiry.InquiryID.ToString();
        Trace.Warn(od);
        //创建该询盘记录
        XPInquiry xpinquiry = new XPInquiry();
        xpinquiry.Insert(inquiry);
 
        od = inquiry.InquiryID.ToString();
        Trace.Warn(od);

        XPInquiryEvent xpInquiryEvent = new XPInquiryEvent();

        //由询盘创建关联信息

        //是否为公开询盘 - 发送至所有工艺匹配的供应商
        if (inquiry.IsPublic)
        {
            string whereText = "";


            DataTable dt = (DataTable)Session["s_selectedCategory_dt"];

            
            if (ddlType.SelectedValue == "1")
            {
                //标准零部件
                foreach (DataRow dr in dt.Rows)
                {
                    whereText = whereText + "([Product] LIKE N'%" + dr["Value"].ToString() + "%') OR";
                }
                whereText = whereText.Remove(whereText.Length - 3);

            }
            else
            {
                //图纸加工
                foreach (DataRow dr in dt.Rows)
                {
                    whereText = whereText + "([Technology] LIKE N'%" + dr["Value"].ToString() + "%') OR";
                }
                whereText = whereText.Trim("OR".ToCharArray());
            }
            XPCompany xpcompany = new XPCompany();
            DataSet ds = xpcompany.SelectDynamic(whereText, "");

            int sum = ds.Tables[0].Rows.Count;
            //Trace.Warn(sum);

            for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                XPInquiryEventInfo inquiryE = new XPInquiryEventInfo();

                var _with3 = inquiryE;
                //.EventID = Guid.NewGuid
                _with3.BuyerCompanyID = inquiry.CompanyID;
                //.EventCode = 0
                //.EventException = ""
                //.EventMessage = ""
                //.EventSequence = 0
                //.EventStatus = "00"
                //.EventTime = DateTime.Now
                //.EventType = 0
                //.Importance = 0
                _with3.InquiryID = inquiry.InquiryID;
                //.IsFlagged = 0
                _with3.QuoteID = Guid.Empty;
                _with3.VendorCompanyID = new Guid(ds.Tables[0].Rows[i]["CompanyID"].ToString());

                xpInquiryEvent.Insert(_with3);
      
            }

        }
        else
        {
            //指定供应商 - 发送至所选定的供应商
            DataTable dt = (DataTable)Session["s_selectedVendors_dt"];

            foreach (DataRow dr in dt.Rows)
            {
                XPInquiryEventInfo inquiryE = new XPInquiryEventInfo();
                var _with4 = inquiryE;
                _with4.InquiryID = inquiry.InquiryID;
                _with4.BuyerCompanyID = inquiry.CompanyID;
                _with4.QuoteID = Guid.Empty;
                _with4.VendorCompanyID = new Guid(dr[0].ToString());

                xpInquiryEvent.Insert(_with4);

            }

            //For i As Integer = 0 To radgridVendorList.SelectedItems.Count - 1
            //    Dim inquiryE As New XPInquiryEvent()
            //    With inquiryE
            //        .InquiryID = inquiry.InquiryID
            //        .BuyerCompanyID = inquiry.CompanyID
            //        .QuoteID = Guid.Empty
            //        .VendorCompanyID = radgridVendorList.SelectedItems(i).OwnerTableView.DataKeyValues(radgridVendorList.SelectedItems(i).ItemIndex)(radgridVendorList.SelectedItems(i).OwnerTableView.DataKeyNames(0))
            //        .Create()

            //    End With
            //Next

        }

        lblMsg.Text = "恭喜您成功的发布了询盘！";

    }

    private static void PerformDragAndDrop(RadTreeViewDropPosition dropPosition, RadTreeNode sourceNode, RadTreeNode destNode)
    {
        if (sourceNode.Equals(destNode) || sourceNode.IsAncestorOf(destNode))
        {
            return;
        }
        sourceNode.Owner.Nodes.Remove(sourceNode);

        switch (dropPosition)
        {
            case RadTreeViewDropPosition.Over:
                // child
                if (!sourceNode.IsAncestorOf(destNode))
                {
                    destNode.Nodes.Add(sourceNode);
                }
                break; // TODO: might not be correct. Was : Exit Select


            case RadTreeViewDropPosition.Above:
                // sibling - above                    
                destNode.InsertBefore(sourceNode);
                break; // TODO: might not be correct. Was : Exit Select

            case RadTreeViewDropPosition.Below:
                // sibling - below
                destNode.InsertAfter(sourceNode);
                break; // TODO: might not be correct. Was : Exit Select

        }
    }

    protected void rtvCategoryTree_NodeDrop(object sender, Telerik.Web.UI.RadTreeNodeDragDropEventArgs e)
    {
        RadTreeNode sourceNode = e.SourceDragNode;


        if (e.HtmlElementID == radgridSelectedCategory.ClientID)
        {
            DataTable dt = (DataTable)Session["s_selectedCategory_dt"];
            foreach (RadTreeNode node in e.DraggedNodes)
            {
                AddRowToGrid(dt, node);
            }
        }
    }
    private void AddRowToGrid(DataTable dt, RadTreeNode node)
    {
        //************************************************************
        //下面代码将解析节点的完全路径，并作为值存入dt中
        //Dim inode As RadTreeNode = node
        //Dim valueofnodes As String = ""
        //While inode.ParentNode IsNot Nothing
        //    valueofnodes = inode.Value & "|" & valueofnodes
        //    inode = inode.ParentNode

        //End While
        //'下面的一行代码决定是否添加根节点作为路径起始
        //'valueofnodes = inode.Value & "|" & valueofnodes

        //For Each dr As DataRow In dt.Rows

        //    If dr.Item("Value").Equals(valueofnodes) Then

        //        Exit Sub

        //    End If
        //Next
        //Dim values As String() = {node.Text, valueofnodes}
        //dt.Rows.Add(values)
        //************************************************************
        //************************************************************
        //下面代码仅仅将节点的值存入dt中
        //下面的一行代码决定是否添加根节点作为路径起始

        //    '此处检查是否与已选节点值相同
        //For Each dr As DataRow In dt.Rows

        //    If dr.Item("Value").Equals(node.Value) Then
        //        Exit Sub
        //    End If
        //Next

        //此处检查是否与已选节点值相同或是以选节点的子节点
        RadTreeNode inode = node;
        while (inode.ParentNode != null)
        {
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["Value"].Equals(inode.Value))
                {
                    return;
                }
            }
            inode = inode.ParentNode;
        }

        string[] values = {
			node.Text,
			node.Value
		};
        dt.Rows.Add(values);
        Session["s_selectedCategory_dt"] = dt;
        //************************************************************

        radgridSelectedCategory.DataSource = dt;
        radgridSelectedCategory.DataBind();
    }

    protected void rblPublic_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        if (rblPublic.SelectedValue == "1")
        {
            pnlVendorSelection.Enabled = false;

        }
        else
        {
            pnlVendorSelection.Enabled = true;
        }
    }

    protected void radgridSelectedCategory_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        DataTable dt = (DataTable)Session["s_selectedCategory_dt"];
        GridDataItem dataitem = ((GridDataItem)e.Item);
        foreach (DataRow dr in dt.Rows)
        {
            if (dr["Value"].ToString() == dataitem["Value"].Text)
            {
                dr.Delete();
                break; // TODO: might not be correct. Was : Exit For

            }
        }

        radgridSelectedCategory.DataSource = dt;
        radgridSelectedCategory.DataBind();
        e.Canceled = true;

    }

    protected void radgridSelectedCategory_ItemCommand(object sender, GridCommandEventArgs e)
    {
        DataTable dt = (DataTable)Session["s_selectedCategory_dt"];
        radgridSelectedCategory.DataSource = dt;
        radgridSelectedCategory.DataBind();
    }

    protected void btnTargetVendor_Click(object sender, System.EventArgs e)
    {

        if (radgridVendorList.SelectedItems.Count > 0)
        {
            DataTable dt = (DataTable)Session["s_selectedVendors_dt"];

            foreach (GridItem gitem in radgridVendorList.SelectedItems)
            {
                bool duplicate = false;
                string vid = gitem.OwnerTableView.DataKeyValues[gitem.ItemIndex][gitem.OwnerTableView.DataKeyNames[0]].ToString();
                string vname = gitem.OwnerTableView.DataKeyValues[gitem.ItemIndex][gitem.OwnerTableView.DataKeyNames[1]].ToString();


                foreach (DataRow dr in dt.Rows)
                {
                    if (dr[0].ToString() == vid)
                    {
                        duplicate = true;
                        break; // TODO: might not be correct. Was : Exit For
                    }
                }
                if (!duplicate)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = vid;
                    dr[1] = vname;
                    dt.Rows.Add(dr);
                }
            }

            rgridTargetVendors.DataSource = dt;
            rgridTargetVendors.DataBind();
        }
    }

    protected void rgridTargetVendors_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        DataTable dt = (DataTable)Session["s_selectedVendors_dt"];
        GridDataItem dataitem = ((GridDataItem)e.Item);
        foreach (DataRow dr in dt.Rows)
        {
            if (dr["CompanyID"] == dataitem.OwnerTableView.DataKeyValues[dataitem.ItemIndex]["CompanyID"])
            {
                dr.Delete();
                break; // TODO: might not be correct. Was : Exit For

            }
        }
        Session["s_selectedVendors_dt"] = dt;
        rgridTargetVendors.DataSource = dt;
        rgridTargetVendors.DataBind();
        e.Canceled = true;
    }

    protected void rgridTargetVendors_ItemCommand(object sender, GridCommandEventArgs e)
    {
        DataTable dt = (DataTable)Session["s_selectedVendors_dt"];
        rgridTargetVendors.DataSource = dt;
        rgridTargetVendors.DataBind();
    }

    protected void ddlSellerRoot_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlSellerRoot.Text  == "own")
        {
            //XPFavoriteVedor favorVedor = new XPFavoriteVedor();
            //DataSet dsFavor = favorVedor.SelectByCompanyID((Guid)Session["s_companyID_guid"]);
            //radgridVendorList.DataSource = dsFavor;
            //radgridVendorList.DataBind();
            radgridVendorList.DataSourceID = "SqlDataSource1";
            radgridVendorList.DataBind();
        }
        else if (ddlSellerRoot.Text  == "all")
        {
            radgridVendorList.DataSourceID  = "odsVendorList";
	        
        }

       
        
    }
}